#!/usr/bin/env python
#-*- coding:utf-8 -*-

'''
mysql 数据模型
    author: cold night
    email : wh_linux@126.com
    date  : 2012-08-06 11:21
'''
from model.get_db import get_db
from model.common import not_empty
from common import dict_to_sql
from common import dict_to_sql_update

__all__=['article_post', 'article_edit', 'article_del', 'category',
         'category_edit', 'category_del', 'comment_add', 'comment_del']


conn = get_db()
cursor = conn.cursor()
POSTS='posts'
POSTSMETA = 'postmeta'
TAGS = 'tags'
COMM = 'comments'
CATE = 'categories'

def _insert_tags(tags, artid):
    cursor.execute("DELETE FROM tags WHERE `artid`=%s;" , (artid,))
    tags = tags.split(',') if type(tags) == str else tags
    for t in tags:
        sql = "INSERT INTO tags(`name`, `artid`) VALUES(%s, %s);"
        cursor.execute(sql,(t, artid))
    conn.commit()

    
def _insert_meta_data(key, value, artid):
    cursor.execute("DELETE FROM postsmeta WHERE `artid`=%s and `key`=%s;" , (artid, key))
    for c in value:
        sql = "INSERT INTO postsmeta(`key`, `value`, `artid`) VALUES(%s, %s, %s);" 
        cursor.execute(sql, (key, c, artid))
    conn.commit()


def _del(_id, table):
    if type(_id) == str or type(_id) == int :
        if ',' in _id:
            for i in _id.split(','):
                cursor.execute("DELETE FROM "+ table +" where `_id`=%s", (i))
        else:
            cursor.execute("DELETE FROM "+ table +" where `_id`=%s", (_id))
    elif type(_id) in (list, tuple):
        for i in _id:
            cursor.execute("DELETE FROM  "+ table +" where `_id`=%s", (i,))
    else:
        raise ValueError("post id must be string/list/tuple")
    conn.commit()

    
    
def article_post(article_dict):
    '''
    '''
    sql = "INSERT INTO " + dict_to_sql(POSTS, article_dict)
    cursor.execute(sql)
    artid = cursor.lastrowid
    _insert_tags(article_dict.get('tags'), artid)
    _insert_meta_data('category', article_dict.get('categories'), artid)
    conn.commit()
    return artid

def article_edit(postid, article_dict):
    '''
    编辑文章
    '''
    sql = dict_to_sql_update(POSTS, article_dict) + " WHERE `_id`="+postid
    print sql
    cursor.execute(sql)
    _insert_tags(article_dict.get('tags'), postid)
    _insert_meta_data('category', article_dict.get('categories'), postid)
    conn.commit()


def article_del(postid):
    not_empty(postid)
    _del(postid, POSTS)



def category(name):
    '''
    分类目录
    '''
    not_empty(name)
    test_sql = 'select * from categories where `name`=%s' 
    param = (name,)
    r = cursor.execute(test_sql, param)
    if r > 0:
        return False
    else:
        sql = 'INSERT INTO categories(`name`) VALUES(%s);'
        r = cursor.execute(sql, param)
        conn.commit()
        return cursor.lastrowid
        

def category_edit(_id, name):
    '''
    编辑分类目录
    '''
    sql = 'UPDATE categories SET `name`=%s where `_id`=%s;'
    param = (name, _id)
    cursor.execute(sql, param)
    conn.commit()

def category_del(_id):
    '''
    删除分类目录
    '''
    sql = 'DELETE FROM postsmeta WHERE `key`=%s and `value`=%s;'
    if type(_id) == list :
        for i in _id:
            param = ('category', i)
            cursor.execute(sql, param)
    else:
        param = ('category', _id)
        cursor.execute(sql, param)
    _del(_id, CATE)
    conn.commit()
    
def comment_add(artid, comment_dict, commid=None):
    '''
    给文章添加评论
    '''
    comment_dict.update(artid=artid)
    sql = 'INSERT INTO ' + dict_to_sql(COMM, comment_dict)
    print sql
    cursor.execute(sql)
    conn.commit()
    

def comment_del(commid, delsub = False):
    '''
    删除评论
    '''
    _ids = []
    if type(commid) == str:
        if ',' in commid:
            for _id in commid.split(',') :
                _ids.append(_id)
        else:
            _ids.append(commid)
    elif type(commid) in (list, tuple):
        _ids = commid
    else:
        raise ValueError("commid must be str/list/tupe")

    if delsub:
        for _id in _ids:
            sql = "DELETE FROM %s WHERE `parentid`='%s'"
            param = (COMM, _id)
            cursor.execute(sql, param)
    _del(_ids, COMM)
    conn.commit()
